const api = 'wss://api.honbiao.com:2348'; // 客户服务器地址
// const api = 'wss://hongbiao.zanboon.com:2348'; // 掌邦服务器地址
import store from '@/store/index.js'
class WebSocket {
	constructor(arg) {
		// 连接是否打开
		this.socketOpen = false;
		// 连接未打开时保存的用户发送的数据
		this.socketMsgQueue = [];
		this.isLink = false;
		// 重连次数限制
		this.limit = 15
		// 是否锁定重连
		this.lockReconnect = false
		this.selfClose = false
	}
	setSelfClose(value) {
		this.selfClose = value
	}
	setLockReconnect (value) {
		this.lockReconnect = value
	}
	initWebSocket(callBack, selfID) {
		const heartBeat = new HeartBeat()
		this.connectSocket()

		this.getSocketMessage((res) => {
			res = JSON.parse(res)
			if (res.type === 'ping') {
				// heartBeat.reset()
				// heartBeat.start()
				// 	.then(() => {
				// 		this.closeConnect({
				// 			reason: '正常关闭',
				// 			code: 1000,
				// 		})
				// 		.then(res => {
				// 			this.selfClose = false
				// 		})
				// 		.catch(err => {
				// 			
				// 		})
				// 	})
			} else {
				if (res.send_id === selfID) {

				} else {
					callBack(res)
				}

			}
		})


		this.socketIsOpen((res) => {
			// heartBeat.reset()
			// heartBeat.start()
			// 	.then(() => {
			// 		this.closeConnect({
			// 			reason: '正常关闭',
			// 			code: 1000,
			// 		})
			// 		.then(res => {
			// 			console.log('心跳连接失败')
			// 		})
			// 		.catch(err => {
			// 			
			// 		})
			// 	})
		})

		this.socketError((err) => {
			this.reConnectSocket()
		})


		this.socketClose(() => {
			if(!this.selfClose) {
				this.reConnectSocket()
			}
		})
	}
	/**
	 * 创建一个 WebSocket 连接
	 */
	connectSocket(params) {
		return new Promise((resolve, reject) => {
			uni.connectSocket({
				url: api + '?token=' + store.getters.getToken,
				method: 'GET',
				success: (res) => {
					if (res.statusCode === 101 || res.statusCode === 200) {
						resolve(res.data)
					} else {
						// uni.showToast({
						// 	icon: 'none',
						// 	title: res.data.message,
						// })
					}
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	}
	/**
	 * 断线重连
	 */
	reConnectSocket() {
		if (this.lockReconnect) return;
		this.lockReconnect = true;
		let timer = null
		if (this.limit > 0) {
			timer = setTimeout(() => {
				this.connectSocket()
				this.lockReconnect = false;
			}, 5000)
			this.limit--
		}
	}
	/**
	 * 监听WebSocket连接打开事件。
	 */
	socketIsOpen(callBack) {
		uni.onSocketOpen((res) => {
			this.socketOpen = true;
			// 连接打开时将保存的数据发送出去
			for (var i = 0; i < this.socketMsgQueue.length; i++) {
				sendSocketMessage(this.socketMsgQueue[i]);
			}
			this.socketMsgQueue = [];
			callBack(res)
		});
	}
	/**
	 * 监听WebSocket连接打开失败事件。
	 */
	socketError(callBack) {
		uni.onSocketError((res) => {
			this.socketOpen = false;
			callBack(res)
		});
	}
	/**
	 * 发送数据
	 */
	sendSocketMessage(msg) {
		if (this.socketOpen) {
			msg['token'] = store.getters.getToken
			msg = JSON.stringify(msg)
			console.log(msg, '12456798')
			return new Promise((resolve, reject) => {
				uni.sendSocketMessage({
					data: msg,
					success: (res) => {
						resolve(res)
					},
					fail: (err) => {
						reject(err)
					}
				});
			})
		} else {
			this.socketMsgQueue.push(msg);
		}
	}
	/**
	 * 接收数据
	 */
	getSocketMessage(callBack) {
		uni.onSocketMessage((res) => {
			callBack(res.data)
		});
	}
	/**
	 * 关闭 WebSocket 连接。传入对象，包括code：一个数字值表示关闭连接的状态号，表示连接被关闭的原因（默认为1000）
	 * 包括reason：一个可读的字符串，表示连接被关闭的原因
	 */
	closeConnect(params) {
		return new Promise((resolve, reject) => {
			uni.closeSocket({
				code: params.code,
				reason: params.reason,
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					reject(err)
				}
			});
		})
	}
	/**
	 * 监听WebSocket关闭。
	 */
	socketClose(callBack) {
		uni.onSocketClose((res) => {
			callBack(res)
		});
	}
}

/**
 * 心跳检测。
 */
class HeartBeat {
	constructor(arg) {
		this.timeOut = 40000
		this.timeOutObj = null
	}
	reset() {
		clearTimeout(this.timeOutObj)
	}
	start() {
		return new Promise((resolve, reject) => {
			this.timeOutObj = setTimeout(() => {
				resolve()
			}, this.timeOut)
		})

	}
}

module.exports = {
	WebSocket,
}
